package com.zm.rpc.server.channel.handler;

import org.apache.log4j.Logger;

import com.zm.rpc.protocol.Header;
import com.zm.rpc.protocol.RpcProtocol;
import com.zm.rpc.server.serializer.ISerializer;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class RpcEncoder extends MessageToByteEncoder<RpcProtocol<Object>>{
    private static final Logger log = Logger.getLogger(RpcEncoder.class);
  
    @Override
    protected void encode(ChannelHandlerContext ctx, RpcProtocol<Object> protocol, ByteBuf byteBuf) throws Exception {
        this.encodeHeader(protocol.getHeader(), byteBuf);
        this.encodeContext(protocol, byteBuf);
        
    }

    private void encodeHeader(Header header, ByteBuf byteBuf){
        byteBuf.writeShort(header.getMagic());
        byteBuf.writeByte(header.getSerialType());
        byteBuf.writeByte(header.getReqType());
        byteBuf.writeLong(header.getReqId());
        byteBuf.writeInt(header.getDataSize());
    }

    private void encodeContext(RpcProtocol<Object> protocol, ByteBuf byteBuf){
        ISerializer serializer = ISerializer.getSerializer(protocol.getHeader().getSerialType());
        byteBuf.writeBytes(serializer.serialize(protocol.getContext()));
    }
    
}
